package com.example.campus.search.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.copyctrl.campus.common.domain.PassageDTO;
import com.copyctrl.campus.common.model.ApiResponse;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author:JH
 * @version:1.0
 */
@RestController
@RequestMapping("/get")
public class FindController {
    @GetMapping("/{str}")
    public ApiResponse test(@PathVariable String str) {
        // 1.准备Request
        SearchRequest request = new SearchRequest("passages");
        // 2.准备DSL
        request.source()
                .query(QueryBuilders.matchQuery("all", str));
        // 2.2.高亮
        request.source().highlighter(new HighlightBuilder().field("title").requireFieldMatch(false));
        request.source().highlighter(new HighlightBuilder().field("summary").requireFieldMatch(false));
        // 3.发送请求
        try (RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://1.14.107.219:9200")
        ));) {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析响应
            return ApiResponse.ofSuccess(handleResponse(response));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private List<PassageDTO> handleResponse(SearchResponse response) {
        List<PassageDTO> result = new ArrayList();
        // 4.解析响应
        SearchHits searchHits = response.getHits();
        // 4.1.获取总条数
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到" + total + "条数据");
        // 4.2.文档数组
        SearchHit[] hits = searchHits.getHits();
        // 4.3.遍历
        // 4.3.遍历
        for (SearchHit hit : hits) {
            // 获取文档source
            String json = hit.getSourceAsString();
            // 反序列化
            PassageDTO passageDTO = JSONUtil.toBean(json, PassageDTO.class);
            // 获取高亮结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtil.isEmpty(highlightFields)) {
                // 根据字段名获取高亮结果
                HighlightField highlightField = highlightFields.get("title");
                if (highlightField != null) {
                    // 获取高亮值
                    String name = highlightField.getFragments()[0].string();
                    // 覆盖非高亮结果
                    passageDTO.setTitle(name);
                }
                // 根据字段名获取高亮结果
                HighlightField highlightField2 = highlightFields.get("summary");
                if (highlightField2 != null) {
                    // 获取高亮值
                    String summary = highlightField2.getFragments()[0].string();
                    // 覆盖非高亮结果
                    passageDTO.setSummary(summary);
                }
                result.add(passageDTO);
            }
        }
        return result;
    }
}
